@file:JvmMultifileClass
@file:JvmName("ColorUtils")

package hos.kotlin

/**
 * <p>Title: IntColorExt </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-07-17 16:16
 * @version : 1.0
 */

/**
 * Set the alpha component of {@code color} to be {@code alpha}.
 *
 * @param alpha Alpha component \([0..255]\) of the color.
 * @return the {@code color} with {@code alpha} component
 */
fun Int.withAlpha(alpha: Int): Int {
    return this and 0x00ffffff or (alpha shl 24)
}

/**
 * Set the alpha component of {@code color} to be {@code alpha}.
 *
 * @param opacity Opacity component \([0..1]\) of the color.
 * @return the {@code color} with {@code alpha} component
 */
fun Int.withOpacity(opacity: Float): Int {
    return this and 0x00ffffff or ((opacity * 255.0f + 0.5f).toInt() shl 24)
}

fun Int.rgb(): String {
    val color = StringBuilder(Integer.toHexString(this and 0x00ffffff))
    while (color.length < 6) {
        color.insert(0, "0")
    }
    return "#$color"
}

fun Int.argb(): String {
    val color = java.lang.StringBuilder(Integer.toHexString(this))
    while (color.length < 6) {
        color.insert(0, "0")
    }
    while (color.length < 8) {
        color.insert(0, "f")
    }
    return "#$color"
}

fun String.toColorInt(): Int {
    // Use a long to avoid rollovers on #ffXXXXXX
    var color: Long = this.substring(1).toLong(16)
    if (this.length == 7) {
        // Set the alpha value
        color = color or 0x00000000ff000000L
    } else require(this.length == 9) { "Unknown color" }
    return color.toInt()
}
